package com.heima.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.Utils.threadlocal.AppThreadLocalUtils;
import com.heima.model.comment.dto.CommentRepayDto;
import com.heima.model.comment.dto.CommentRepayLikeDto;
import com.heima.model.comment.dto.CommentRepaySaveDto;
import com.heima.model.comment.pojo.ApComment;
import com.heima.model.comment.pojo.ApCommentRepay;
import com.heima.model.comment.pojo.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by ZYJ on 2021/6/5 23:23
 */
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;

    /**
     * 加载评论回复列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if(dto.getSize() == null || dto.getSize()<1){
            dto.setSize(10);
        }
        //根据评论id 最小时间 size 按照创建时间降序查询数据
        Query query = Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate())
        ).limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentRepay> apCommentRepayList = this.mongoTemplate.find(query, ApCommentRepay.class);
        //判断用户是否登录 没登录直接返回数据
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null|| CollUtil.isEmpty(apCommentRepayList)){
            return ResponseResult.okResult(apCommentRepayList);
        }
        //如果登录了 判断那些回复登录用户点过赞
        List<String> commentRepayIds = apCommentRepayList.stream()
                .map(ApCommentRepay::getId).collect(Collectors.toList());
            //查询这其中的用户点过赞的评论回复
        List<ApCommentRepayLike> apCommentRepayLikes = this.mongoTemplate.find(Query.query(Criteria
                .where("commentRepayId").in(commentRepayIds)
                .and("authorId").is(user.getId())), ApCommentRepayLike.class);
            //抽取这其中的用户点过赞的评论回复的id
        List<String> repayLikeIdList = apCommentRepayLikes.stream()
                .map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());

        List<ApCommentRepayVo> apCommentRepayVoList = apCommentRepayList.stream().map(apCommentRepay -> {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtil.copyProperties(apCommentRepay, apCommentRepayVo);

            if (repayLikeIdList.contains(apCommentRepay.getId())) {
                apCommentRepayVo.setOperation((short) 0);
            }
            return apCommentRepayVo;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(apCommentRepayVoList);
    }

    /**
     * 保存评论的回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //检查参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据评论id查询评论信息
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "该评论不见了");
        }
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "获取用户信息失败");
        }
        //保存回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(apComment.getId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //将对应评论回复数量+1

        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    /**
     * 点赞  回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCommentRepay commetRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commetRepay == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "此回复评论不见了");
        }
        //查询是否点过赞 查询点赞集合 如果有点赞数据并且operation为0 说明点过赞
        Query query = Query.query(Criteria
                .where("authorId").is(user.getId())
                .and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (commentRepayLike != null && dto.getOperation() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
        }
        //根据方式进行对应处理
        if (dto.getOperation() == 0) {
            //点赞操作  评论回复点赞数量+1 保存点赞信息
            commetRepay.setLikes(commetRepay.getLikes() + 1);
            mongoTemplate.save(commetRepay);

            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(commetRepay.getId());
            apCommentRepayLike.setOperation((short)0);

        }else {
            //取消点赞 评论回复的数量-1 删除点赞信息
            commetRepay.setLikes(commetRepay.getLikes() <1 ? 0 :commetRepay.getLikes()-1);

            mongoTemplate.remove(query,ApCommentRepayLike.class);
        }
        //返回最新点赞数量
        Map map = new HashMap();
        map.put("likes",commetRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
